package com.runmonk.core.study.handler;

import com.runmonk.core.dto.ApiResponse;
import com.runmonk.core.exception.NoLoginException;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;


/**
 * 接口异常统一处理
 *
 * @author shenwei
 */
@ControllerAdvice
public class NoLoginExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(NoLoginExceptionHandler.class);

    /**
     * 登录超时或未登录
     */
    @ExceptionHandler(value = NoLoginException.class)
    public Object handleNoLoginExceptionExtent(NoLoginException ex, HttpServletRequest request) {
        String xRequestedWith = request.getHeader("X-Requested-With");
        //String loginUrl = webContextUtils.getAppServer(request) + "/login";
        //if (StringUtils.equalsIgnoreCase("XMLHttpRequest", xRequestedWith)) {
        ApiResponse res = ApiResponse.create();
        res.setCode(ex.getCode());
        res.setMsg(ex.getMessage());
        //res.setData(loginUrl);
        ResponseEntity<ApiResponse> responseEntity = new ResponseEntity<ApiResponse>(res, HttpStatus.OK);
        return responseEntity;
        //} else {
        //return "redirect:" + loginUrl;
        //}
    }




//    /**
//     * 异常信息的渲染
//     */
//    @Override
//    protected Object handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, WebRequest request) {
//        Object returnV = null;
//        setExceptionToRequest(request, ex);
//        String xRequestedWith = request.getHeader("X-Requested-With");
//        if (StringUtils.equalsIgnoreCase("XMLHttpRequest", xRequestedWith)) { //Ajax，返回 json
//            returnV = new ResponseEntity<Object>(body, headers, HttpStatus.OK);
//        } else { //页面
//            request.setAttribute("page_msg", body, 1);
//            returnV = "/commons/msg";
//        }
//        return returnV;
//    }
}
